package com.wwz.leetcode;

import org.junit.Test;

/**
 * 字符串转换整数 (atoi)
 * 快手一面算法题 2022.11.17
 */
public class LeetCode8 {

    public int myAtoi(String s) {
        int left = 0;
        // 去除前导空格
        while (left < s.length()) {
            if (s.charAt(left) != ' ') {
                break;
            }
            left++;
        }
        // 全是空格就给个0
        if (left >= s.length())
            return 0;
        // 左边第一个字符
        char c = s.charAt(left);
        if (c >= '0' && c <= '9' || c == '+' || c == '-') {
            int right = left + 1;
            while (right < s.length() && s.charAt(right) >= '0' && s.charAt(right) <= '9') {
                right++;
            }
            // 排除符号位
            if (c == '-' || c == '+') {
                left++;
            }
            long ans = 0;
            for (int i = left; i < right; i++) {
                int temp = s.charAt(i) - '0';
                ans = ans * 10 + temp;
                if (ans > Integer.MAX_VALUE) {
                    break;
                }
            }
            if (c == '-') ans = -ans;
            if (ans > Integer.MAX_VALUE) return Integer.MAX_VALUE;
            if (ans < Integer.MIN_VALUE) return Integer.MIN_VALUE;
            return (int) ans;
        }
        return 0;
    }

    @Test
    public void test() {
        //System.out.println(myAtoi("words and 987"));
        System.out.println(myAtoi("4193 with words"));
    }
}
